package com.yyfax.ph.personal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IEvent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.network.NetworkTool;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseFragment;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.Utils;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.common.widgets.shortbadger.ShortcutBadger;
import com.yyfax.ph.personal.about.AboutUsActivity;
import com.yyfax.ph.personal.about.branch.BranchActivity;
import com.yyfax.ph.personal.authority.bankcard.BankCardEvent;
import com.yyfax.ph.personal.authority.bankcard.view.activity.BindCardActivity;
import com.yyfax.ph.personal.authority.bankcard.view.activity.GetBindCardActivity;
import com.yyfax.ph.personal.bindapply.BindApplyActivity;
import com.yyfax.ph.personal.message.MessageActivity;
import com.yyfax.ph.personal.mymoney.cash.CashActivity;
import com.yyfax.ph.personal.mymoney.withdraw.WithDrawActivity;
import com.yyfax.ph.personal.settings.BankCardPresenter;
import com.yyfax.ph.personal.settings.SettingActivity;
import com.yyfax.ph.personal.subaccount.SubAccountActivity;
import com.yyfax.ph.web.WebActivity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * "我的"功能模块
 * Created by zhangxian on 2017/11/4.<br>
 * Copyright 2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class PersonCenterFragment extends BaseFragment implements OnClickListener,
		PersonCenterPresenter.View, BankCardPresenter.View {
	private static final String TAG = PersonCenterFragment.class.getSimpleName();
	private static final int LOADER_ID_BANKCARD = 155;

	private static final int LOADER_ID_PERSON = 10011;
	private static final String STR_HIDDEN_MONEY_FLAG = "***";
	private static final int EYE_ICON_PLUS = 1;
	private static final int EYE_ICON_DEFAULT = 0;
	private static final int EYE_ICON_MINUS = -1;

	boolean changeAccount = false;
	/**
	 * 子账户未实名认证展示的头部
	 */
	private View mNotVerifiedHeaderView;
	@BindView(R.id.not_verified_header)
	ViewStub mNotVerifiedHeader;
	/**
	 * 立即认证
	 */
	TextView mCertificationTv;

	/**
	 * 子账户已经实名认证展示的头部
	 */
	private View mVerifiedHeaderView;
	@BindView(R.id.verified_header)
	ViewStub mVerifiedHeader;
	/**
	 * 待提现佣金
	 */
	TextView mMoneyTv;
	/**
	 * 眼睛按钮
	 */
	CheckBox mEyeCb;
	/**
	 * 查看明细
	 */
	TextView mViewDetailTv;
	/**
	 * 立即提现
	 */
	TextView mImmediatePresentTv;

	/**
	 * 母账户展示的头部
	 */
	private View mMotherAccountHeaderView;
	@BindView(R.id.mother_account_header)
	ViewStub mMotherAccountHeader;
	/**
	 * 公司名称
	 */
	TextView mCompanyTv;
	/**
	 * 子账号管理
	 */
	TextView mSubAccountTv;
	/**
	 * 绑定处理
	 */
	RelativeLayout mBindingProcessingRl;

	/**
	 * 有新的绑定处理的提示
	 */
	ImageView mBindingProcessingBadgeIv;

	/**
	 * 未读消息数目
	 */
	@BindView(R.id.message_count_tv)
	TextView mMessageCountTv;

	private String mUserPhone;
	private String mUserName = YJPH.getInstance().getPreferenceManager().getUserName();
	private String mStayWithdrawMoney = UNKNOWN_MONEY_AMOUNT;
	private int mUserType = YJPH.getInstance().getPreferenceManager().getUserType(0);

	Unbinder unbinder;

	private PersonCenterPresenter mPresenter;
	private BankCardPresenter mBankCardPresenter;
	private boolean mIsBackstageClosed = false; // 后台是否关闭
	private int mHasPlusTopMargin = 0;

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		EventAgent.register(this);
		getLoaderManager().initLoader(LOADER_ID_PERSON, null, this);
		getLoaderManager().initLoader(LOADER_ID_BANKCARD, null, this);
	}

	@Override
	public void onDetach() {
		EventAgent.unregister(this);
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_PERSON);
		getLoaderManager().destroyLoader(LOADER_ID_BANKCARD);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_PERSON:
				return new PresenterLoader<>(getActivity(), new PersonCenterPresenter.Generator());
			case LOADER_ID_BANKCARD:
				return new PresenterLoader<>(getActivity(), new BankCardPresenter.Generator());
			default:
				break;
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_PERSON:
				mPresenter = (PersonCenterPresenter) data;
				mPresenter.attach(this);
				break;
			case LOADER_ID_BANKCARD:
				mBankCardPresenter = (BankCardPresenter) data;
				mBankCardPresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mUserPhone = YJPH.getInstance().getPreferenceManager().getUserPhone();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.person_center_fragment, null);
		unbinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		CLog.i(TAG, "PersonCenterFragment : onViewCreated");
		setHeaderView();
	}

	private void setHeaderView() {
		mUserType = YJPH.getInstance().getPreferenceManager().getUserType(0);
		mUserName = YJPH.getInstance().getPreferenceManager().getUserName();
		if (mNotVerifiedHeaderView != null) {
			mNotVerifiedHeaderView.setVisibility(View.GONE);
		}
		if (mVerifiedHeaderView != null) {
			mVerifiedHeaderView.setVisibility(View.GONE);
		}
		if (mMotherAccountHeaderView != null) {
			mMotherAccountHeaderView.setVisibility(View.GONE);
		}

		//如果是个人账户
		if (mUserType == Constants.TYPE_SUB_ACCOUNT) {
			//如果未实名认证
			if (TextUtils.isEmpty(mUserName)) {
				if (mNotVerifiedHeaderView != null) {
					mNotVerifiedHeaderView.setVisibility(View.VISIBLE);
					return;
				}
				mNotVerifiedHeaderView = mNotVerifiedHeader.inflate();
				mCertificationTv = (TextView) mNotVerifiedHeaderView.findViewById(R.id.cetification_tv);
				mCertificationTv.setOnClickListener(this);
			} else {
				//如果已经实名认证
				if (mVerifiedHeaderView != null) {
					mVerifiedHeaderView.setVisibility(View.VISIBLE);
					return;
				}
				mVerifiedHeaderView = mVerifiedHeader.inflate();
				mMoneyTv = (TextView) mVerifiedHeaderView.findViewById(R.id.money_tv);
				mEyeCb = (CheckBox) mVerifiedHeaderView.findViewById(R.id.eyes_cb);
				mViewDetailTv = (TextView) mVerifiedHeaderView.findViewById(R.id.view_detail_tv);
				mImmediatePresentTv = (TextView) mVerifiedHeaderView.findViewById(R.id.immediate_present_tv);
				mEyeCb.setOnClickListener(this);
				mViewDetailTv.setOnClickListener(this);
				mImmediatePresentTv.setOnClickListener(this);
			}
		} else if (mUserType == Constants.TYPE_MOTHER_ACCOUNT) {
			//如果是企业账户
			if (mMotherAccountHeaderView != null) {
				mMotherAccountHeaderView.setVisibility(View.VISIBLE);
				mCompanyTv.setText(mUserName);
				return;
			}
			mMotherAccountHeaderView = mMotherAccountHeader.inflate();
			mCompanyTv = (TextView) mMotherAccountHeaderView.findViewById(R.id.company_tv);
			mCompanyTv.setText(mUserName);
			mSubAccountTv = (TextView) mMotherAccountHeaderView.findViewById(R.id.sub_account_tv);
			mBindingProcessingRl = (RelativeLayout) mMotherAccountHeaderView.findViewById(R.id.binding_processing_rl);
			mBindingProcessingBadgeIv = (ImageView) mMotherAccountHeaderView.findViewById(R.id.bindind_processing_badge_iv);
			mSubAccountTv.setOnClickListener(this);
			mBindingProcessingRl.setOnClickListener(this);
		}
	}

	/**
	 * 接收绑卡成功的消息
	 */
	@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
	public void onEventMainThread(BankCardEvent event) {
		EventAgent.removeStickyEvent(event);
		CLog.i(TAG, "onEventMainThread(BankCardEvent)");
		if (mNotVerifiedHeaderView != null) {
			mNotVerifiedHeaderView.setVisibility(View.GONE);
		}
		if (mVerifiedHeaderView != null) {
			mVerifiedHeaderView.setVisibility(View.GONE);
		}
		if (mMotherAccountHeaderView != null) {
			mMotherAccountHeaderView.setVisibility(View.GONE);
		}
		//如果已经实名认证
		if (mVerifiedHeaderView != null) {
			mVerifiedHeaderView.setVisibility(View.VISIBLE);
			return;
		}
		if (mVerifiedHeader == null)
			return;
		mVerifiedHeaderView = mVerifiedHeader.inflate();
		mMoneyTv = (TextView) mVerifiedHeaderView.findViewById(R.id.money_tv);
		mPresenter.checkBalance();
		mEyeCb = (CheckBox) mVerifiedHeaderView.findViewById(R.id.eyes_cb);
		mViewDetailTv = (TextView) mVerifiedHeaderView.findViewById(R.id.view_detail_tv);
		mImmediatePresentTv = (TextView) mVerifiedHeaderView.findViewById(R.id.immediate_present_tv);
		mEyeCb.setOnClickListener(this);
		mViewDetailTv.setOnClickListener(this);
		mImmediatePresentTv.setOnClickListener(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		if (changeAccount) {
			changeAccount = false;
			mStayWithdrawMoney = UNKNOWN_MONEY_AMOUNT;
			setHeaderView();
		}
		if (YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			if (mUserType == Constants.TYPE_MOTHER_ACCOUNT) {
				mPresenter.getApplyCount();
			} else if (mUserType == Constants.TYPE_SUB_ACCOUNT && !TextUtils.isEmpty(mUserName)) {
				mPresenter.checkBalance();
			}
			mPresenter.getMsgCount();
		}


	}

	@Override
	public void onDestroyView() {
		unbinder.unbind();
		super.onDestroyView();
	}

	@OnClick({R.id.message_ll,
			R.id.search_the_store_tv, R.id.common_problem_tv, R.id.about_us_tv,
			R.id.account_settings_tv})
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			//立即认证
			case R.id.cetification_tv:
				BindCardActivity.start(getActivity());
				break;
			//查看明细
			case R.id.view_detail_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E005);
				CashActivity.start(getActivity());
				break;
			case R.id.eyes_cb:
				//眼睛可见
				hideAccountMoney();
				break;
			//立即提现
			case R.id.immediate_present_tv:
				gotoWithDrawActivity();
				break;
			//子账号管理
			case R.id.sub_account_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E001);
				SubAccountActivity.start(getActivity());
				break;
			//绑定处理
			case R.id.binding_processing_rl:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E002);
				BindApplyActivity.start(getActivity());
				break;
			//消息
			case R.id.message_ll:
				MessageActivity.start(getActivity());
				break;
			//网点查询
			case R.id.search_the_store_tv:
				BranchActivity.start(getActivity());
				break;
			//常见问题
			case R.id.common_problem_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E015);
				WebActivity.start(getActivity(), getString(R.string.common_problem), WebActivity.TYPE_COMMON_PROBLEM);
				break;
			//关于我们
			case R.id.about_us_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E018);
				AboutUsActivity.start(getActivity());
				break;
			//账号设置
			case R.id.account_settings_tv:
				SettingActivity.start(getActivity());
				break;
			default:
				break;
		}
	}

	/**
	 * 跳转提现
	 */
	public void gotoWithDrawActivity() {
		// 如果后台未关闭，网络可用且返回数据正常,则跳转提现
		if (NetworkTool.isNetworkAvailable(getActivity())) {
			mBankCardPresenter.getBindBankCardInfo();//获取绑定银行卡信息
		} else {
			showToast(R.string.common_network_unavailable);
		}
	}

	private void hideAccountMoney() {
		boolean isChecked = mEyeCb.isChecked();
		if (isChecked) {//可见
			mMoneyTv.setText(TextUtils.equals(UNKNOWN_MONEY_AMOUNT, mStayWithdrawMoney) ? mStayWithdrawMoney : Utils.getFormatMoney(mStayWithdrawMoney));
			resolveEyeIconPosition(true);
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants
					.SP_KEY_HIDDEN_MONEY_AMOUNT, false);
		} else {
			mMoneyTv.setText(STR_HIDDEN_MONEY_FLAG);
			resolveEyeIconPosition(false);
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants
					.SP_KEY_HIDDEN_MONEY_AMOUNT, true);
		}
	}

	private void resolveEyeIconPosition(boolean show) {
		ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) mMoneyTv.getLayoutParams();
		if (show) {
			if (mHasPlusTopMargin == EYE_ICON_PLUS) {
				mHasPlusTopMargin = EYE_ICON_MINUS;
				param.topMargin -= DensityUtil.dip2px(getActivity(), 7);
			}
		} else {
			if (mHasPlusTopMargin == EYE_ICON_DEFAULT || mHasPlusTopMargin == EYE_ICON_MINUS) {
				mHasPlusTopMargin = EYE_ICON_PLUS;
				param.topMargin += DensityUtil.dip2px(getActivity(), 7);
			}
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		mIsBackstageClosed = true;
	}

	@Override
	public void getMsgCountResult(int count) {
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_UNREAD_PUSH_MESSAGE_COUNT, count);
		if (count > 0) {
			ShortcutBadger.applyCount(YJPH.getInstance(), count);
			mMessageCountTv.setText(getString(R.string.message_count_hint, count));
		} else {
			ShortcutBadger.removeCount(YJPH.getInstance());
			mMessageCountTv.setText(null);
		}
	}

	@Override
	public void getBalanceResult(String unWithDrawMoney, String bankCode, String bankCard) {
		try {
			if (Double.valueOf(unWithDrawMoney) < 0 || Double.valueOf(unWithDrawMoney) < 0) {//负数则显示--，且不能点击
				mImmediatePresentTv.setEnabled(false);
				mMoneyTv.setText(UNKNOWN_MONEY_AMOUNT);
				resolveEyeIconPosition(true);
				return;
			}
		} catch (NumberFormatException e) {
			return;
		}

		CLog.i(TAG, "unWithDrawMoney = " + unWithDrawMoney);
		mStayWithdrawMoney = unWithDrawMoney;
		if (YJPH.getInstance().getPreferenceManager().isHiddenMoneyAmount()) {
			mMoneyTv.setText(STR_HIDDEN_MONEY_FLAG);
			resolveEyeIconPosition(false);
			mEyeCb.setChecked(false);
		} else {
			mMoneyTv.setText(TextUtils.equals(UNKNOWN_MONEY_AMOUNT, mStayWithdrawMoney) ? mStayWithdrawMoney : Utils.getFormatMoney(mStayWithdrawMoney));
			resolveEyeIconPosition(true);
			mEyeCb.setChecked(true);
		}
		mIsBackstageClosed = false;
	}

	/**
	 * 获取新消息条数
	 */
	@Override
	public void getApplyCountResult(int count) {
		if (mBindingProcessingBadgeIv != null) {
			if (count > 0) {
				mBindingProcessingBadgeIv.setVisibility(View.VISIBLE);
			} else {
				mBindingProcessingBadgeIv.setVisibility(View.GONE);
			}
		}
		mIsBackstageClosed = false;
	}

	@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
	public void onEventMainThread(IEvent.LoginSuccessEvent event) {
		CLog.i(TAG, "onEventMainThread(LoginSuccessEvent)");
		switch (event.id) {
			case IEvent.LoginSuccessEvent.CODE_LOGIN_SUCCESS:
				EventAgent.removeStickyEvent(event);
				changeAccount = true;
				break;
		}
	}

	@Override
	public void getBankCardInfoSuccess(final String name, final String certId, final String cardId, final String bank, final String bankCode) {
		//if parameters are all empty, that means this account hasn't bind bank card yet
		if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(certId) && !TextUtils.isEmpty(cardId) && !TextUtils.isEmpty(bank)) {//已经绑定银行卡
			String money = mStayWithdrawMoney;
			if (TextUtils.isEmpty(mStayWithdrawMoney) || TextUtils.equals(UNKNOWN_MONEY_AMOUNT, mStayWithdrawMoney)){
				money = "0.00";
			}

			WithDrawActivity.start(getActivity(), money, bankCode, cardId);
		} else {          //尚未绑定银行卡
			showTipsDialog(
					getString(R.string.choose_bind_card_tips),
					R.string.no, R.string.bind_now,
					new DialogBase.BottomTwoClickListener() {
						@Override
						public void onCancelClick(DialogBase dialog) {
							dialog.dismiss();
						}

						@Override
						public void onConfirmClick(DialogBase dialog) {
							dialog.dismiss();
							Intent intent = new Intent(getActivity(), BindCardActivity.class);
							intent.putExtra(GetBindCardActivity.NAME, name);
							intent.putExtra(GetBindCardActivity.CARD_ID, certId);
							BindCardActivity.start(getActivity(), intent);
						}
					}
			);
		}
	}

	@Override
	public void getBankCardInfoFailed(String tips) {
		showToast(tips);
	}
}
